package org.jianfa.rpc.server.bootstrap;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import org.jianfa.learn.common.request.RpcRequest;
import org.jianfa.learn.common.serializer.JSONSerializer;
import org.jianfa.rpc.server.decoder.RpcDecoder;
import org.jianfa.rpc.server.handler.UserServiceHandler;
import org.jianfa.learn.common.zookeeper.ZookeeperRegistryCenter;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

@Service
public class ServerBoot implements ApplicationContextAware {

    private ApplicationContext applicationContext;

    @Value("${netty.port}")
    private Integer nettyPort;

    private NioEventLoopGroup  bossGroup;

    private NioEventLoopGroup workGroup;

    private ZookeeperRegistryCenter zookeeperRegistryCenter;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    @PostConstruct
    public void postConstruct() throws Exception{
        System.out.println(String.format("服务%s:%d启动。", "127.0.0.1", nettyPort));

        //1.创建两个线程池对象
        bossGroup = new NioEventLoopGroup();
        workGroup = new NioEventLoopGroup();

        //2.创建服务端的启动引导对象
        ServerBootstrap serverBootstrap = new ServerBootstrap();

        //3.配置启动引导对象
        serverBootstrap.group(bossGroup,workGroup)
                //设置通道为NIO
                .channel(NioServerSocketChannel.class)
                //创建监听channel
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception {
                        //获取管道对象
                        ChannelPipeline pipeline = nioSocketChannel.pipeline();
                        //给管道对象pipeLine 设置编码
                        pipeline.addLast(new StringEncoder());
                        pipeline.addLast(new RpcDecoder(RpcRequest.class, new JSONSerializer()));
                        //把我们自顶一个ChannelHander添加到通道中
                        pipeline.addLast(new UserServiceHandler(applicationContext));
                    }
                });

        //4.绑定端口
        serverBootstrap.bind(nettyPort).sync();

        //5.注册到zookeeper
        zookeeperRegistryCenter = new ZookeeperRegistryCenter();

        //5.1 初始化
        zookeeperRegistryCenter.init();

        //5.2 在servers下面管理所有的实例
        String serversPath = "/servers";
        zookeeperRegistryCenter.persist(serversPath);

        //5.3 把自己注册到servers下面
        String instancePath = String.format("/servers/%s:%d", "127.0.0.1", nettyPort);
        zookeeperRegistryCenter.persistEphemeral(instancePath);
    }

    @PreDestroy
    public void preDestroy() throws Exception{
        System.out.println(String.format("服务%s:%d销毁。", "127.0.0.1", nettyPort));

        workGroup.shutdownGracefully();
        bossGroup.shutdownGracefully();
        zookeeperRegistryCenter.close();
    }
}
